package com.achievement.project.system.course.controller;

import java.util.List;
import java.util.Map;

import com.achievement.project.system.choose.domain.CourseChoose;
import com.achievement.project.system.choose.service.ICourseChooseService;
import com.achievement.project.system.score.domain.Score;
import com.achievement.project.system.score.service.IScoreService;
import com.achievement.project.system.student.domain.Student;
import com.achievement.project.system.student.service.IStudentService;
import com.achievement.project.system.teacher.domain.Teacher;
import com.achievement.project.system.teacher.service.ITeacherService;
import com.achievement.project.system.user.domain.UserRole;
import io.swagger.models.auth.In;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.achievement.framework.aspectj.lang.annotation.Log;
import com.achievement.framework.aspectj.lang.enums.BusinessType;
import com.achievement.project.system.course.domain.Course;
import com.achievement.project.system.course.service.ICourseService;
import com.achievement.framework.web.controller.BaseController;
import com.achievement.framework.web.domain.AjaxResult;
import com.achievement.common.utils.poi.ExcelUtil;
import com.achievement.framework.web.page.TableDataInfo;

/**
 * 课程管理Controller
 *
 * @author zkai
 * @date 2021-04-24
 */
@Controller
@RequestMapping("/system/course")
public class CourseController extends BaseController
{
    private String prefix = "system/course";

    @Autowired
    private ICourseService courseService;
    @Autowired
    private IStudentService studentService;

    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private IScoreService scoreService;

    @Autowired
    private ICourseChooseService courseChooseService;


    @RequiresPermissions("system:course:view")
    @GetMapping()
    public String course()
    {
        return prefix + "/course";
    }

    /**
     * 查询课程管理列表
     */
    @RequiresPermissions("system:course:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Course course)
    {
        startPage();
        List<Course> list = courseService.selectCourseList(course);
        return getDataTable(list);
    }

    /**
     * 导出课程管理列表
     */
    @RequiresPermissions("system:course:export")
    @Log(title = "课程管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Course course)
    {
        List<Course> list = courseService.selectCourseList(course);
        ExcelUtil<Course> util = new ExcelUtil<Course>(Course.class);
        return util.exportExcel(list, "课程管理数据");
    }

    /**
     * 新增课程管理
     */
    @GetMapping("/add/{sId}")
    public String add(@PathVariable("sId") Long sId, ModelMap mmap)
    {
        List<CourseChoose> courseChooses = courseChooseService.selectCourseChooseList(new CourseChoose());
        Student student = studentService.selectStudentById(sId);
        mmap.put("student",student);
        mmap.put("courseChooses",courseChooses);
        return prefix + "/add";
    }

    /**
     * 新增保存课程管理
     */
    @RequiresPermissions("system:course:add")
    @Log(title = "课程管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Course course)
    {
        Long courseId = course.getCourseId();
        Long sId = course.getsId();
        Student student = studentService.selectStudentById(sId);

        //学生在保存课程的时候，同时将教师的id保存至表中
        //根据现有规则  一位教师教授一门课程
        Teacher teacher = teacherService.selectTeacherByCourseId(courseId,student.getClassId());
        if (teacher==null){
            return error("该课程未绑定同班级下教师信息");
        }else {
            course.setpId(teacher.getId().toString());
            course.setcTypeId(Long.valueOf(teacher.getCourseTypeId()));
            //判断该学生有无重复绑定相同课程
            Course course1 = courseService.selectCourseByIdAndSid(course.getCourseId(), course.getsId());
            if (course1 != null) {
                return error("课程添加失败，相同课程已存在");
            } else {


                //先将课程与学生  教师之间关系绑定  插入中间表中
                int i = courseService.insertCourse(course);
                //随后将学生相关信息与教师绑定 存入成绩表中
                List<Map<String, Object>> scopeListByCourseId = courseService.getScopeListByCourseId(courseId, course.getsId());
                if (!scopeListByCourseId.isEmpty()) {
                    for (Map<String, Object> map : scopeListByCourseId
                    ) {
                        Score score = new Score();
                        score.setStudentId(Long.parseLong(map.get("student_id").toString()));
                        score.setSno(map.get("NO").toString());
                        score.setSname(map.get("NAME").toString());
                        score.setGradeId(map.get("grade_id").toString());
                        score.setProfessionalId(map.get("professional_id").toString());
                        score.setClassId(map.get("class_id").toString());
                        score.setCourseId(Long.parseLong(map.get("course_id").toString()));
                        score.setcTypeId(Long.parseLong(map.get("c_type_id").toString()));
                        score.setTeacherId(Long.parseLong(map.get("teacher_id").toString()));
                        scoreService.insertScore(score);
                    }
                }
                return toAjax(i);
            }
        }
    }

    /**
     * 修改课程管理
     */
    @GetMapping("/edit/{courseId}")
    public String edit(@PathVariable("courseId") Long courseId, ModelMap mmap)
    {
        Course course = courseService.selectCourseById(courseId);
        mmap.put("course", course);
        return prefix + "/edit";
    }

    /**
     * 修改保存课程管理
     */
    @RequiresPermissions("system:course:edit")
    @Log(title = "课程管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Course course)
    {
        return toAjax(courseService.updateCourse(course));
    }

    /**
     * 删除课程管理
     */
    @RequiresPermissions("system:course:remove")
    @Log(title = "课程管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(courseService.deleteCourseByIds(ids));
    }

    @Log(title = "删除对应学生的课程", businessType = BusinessType.GRANT)
    @PostMapping("/deleteById")
    @ResponseBody
    public AjaxResult deleteById(Course course)
    {
        //同步删除已经插入到成绩表中的数据
        scoreService.deleteScoreByCourse(course.getsId(),course.getCourseId());
        return toAjax(courseService.deleteById(course));
    }


}
